import dataPreferences from '@ohos.data.preferences';
import { BusinessError } from '@ohos.base';
import { Context } from '@ohos.abilityAccessCtrl';

export class CacheManager {
  //Preference本身做了内存缓存
  static context: Context;

  static initClass(context: Context) {
    CacheManager.context = context;
    if (!CacheManager._sharedInstance) {
      CacheManager._sharedInstance = new CacheManager("shared");
    }
  }

  private preference!: dataPreferences.Preferences
  private name: string;
  private static _sharedInstance: CacheManager;

  public static sharedInstance() {
    return CacheManager._sharedInstance;
  }

  //创建实例后,不能直接使用,因为是异步初始化好的.
  //可以使用首屏进行处理,在这里进行所有的初始化操作.
  constructor(name: string) {
    this.name = name;
    dataPreferences.getPreferences(CacheManager.context, name, (err: BusinessError, preferences: dataPreferences.Preferences) => {
      this.preference = preferences;
    });
  }

  /**
   * TIPS:
   * 必须调用flush否则不会保存成功.
   * @param key
   * @param object
   */
  set<T>(key: string, object: T) {
    // dataReference.va
    // this.preference.putSync(key,object);
    // this.preference.flush();
  }

  /**
   * 保存T类型的json数据
   * @param key
   * @param object
   */
  saveJson<T>(key: string, object: T) {
    this.preference.putSync(key, `${JSON.stringify(object)}`);
    this.preference.flush();
  }

  // get(key:string) : any {
  //   return null;
  // }

  saveString(key: string, object: string) {
    this.preference.putSync(key, object);
    this.preference.flush();
  }

  save(key: string, value: string | boolean | number) {
    this.preference.putSync(key, value);
    this.preference.flush();
  }

  saveBoolean(key: string, b: boolean) {
    this.preference.putSync(key, b);
    this.preference.flush();
  }

  fetchString(key: string): string {
    let val = this.preference.getSync(key, "");
    return val.toString();
  }

  fetchNumber(key: string): number | null {
    let val: string = this.fetchString(key);
    if (val.length == 0) {
      return null;
    }
    let ret = Number.parseInt(val);
    if (Number.isNaN(ret)) {
      return null;
    }
    return ret;
  }

  fetchBool(key: string, defaultValue: boolean): boolean | null {
    let val: string = this.fetchString(key);
    if (val.length == 0) {
      return null;
    }
    let ret = Number.parseInt(val) == 1;
    if (Number.isNaN(ret)) {
      return null;
    }
    return ret;
  }

  remove(key: string) {
    let val = this.preference
  }
}